package com.itheima.sh.controller;

import com.itheima.sh.user.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    DiscoveryClient discoveryClient;


    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallback")
    public User queryById(@PathVariable("id") String id){
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance instance = instances.get(0);
//        URI uri = instance.getUri();
//
//        String url = uri+"/user/" + id;
        if ("itheima".equals(id)) {
            throw new RuntimeException("itheima");
        }
        String url = "http://user-service/user/"+id;
        // 调用RestTemplate的getForObject方法，指定url地址和返回值类型
        User user = restTemplate.getForObject(url, User.class);

        return user;
    }
    public User queryByIdFallback(String id){
        User user = new User();
        user.setNickName("服务不可用");
        return user;
    }
}
